All files / web/src/app/practice/[studentId] PracticeClient.tsx

0% Statements 0/1062
0% Branches 0/1
0% Functions 0/1
0% Lines 0/1062

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
'use client'

import { useRouter, useSearchParams } from 'next/navigation'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useToast } from '@/components/common/ToastContext'
import { useMyAbacus } from '@/contexts/MyAbacusContext'
import { PageWithNav } from '@/components/PageWithNav'
import {
  ActiveSession,
  type AttemptTimingData,
  type BroadcastState,
  type GameBreakHudData,
  PracticeErrorBoundary,
  PracticeSubNav,
  type SessionHudData,
} from '@/components/practice'
import { GameBreakScreen } from '@/components/practice/GameBreakScreen'
import { GameBreakResultsScreen } from '@/components/practice/GameBreakResultsScreen'
import type { GameResultsReport } from '@/lib/arcade/game-sdk/types'
import type { Player } from '@/db/schema/players'
import type {
  GameBreakSettings,
  SessionHealth,
  SessionPart,
  SessionPlan,
  SessionRetryState,
  SlotResult,
} from '@/db/schema/session-plans'
import { getSlotRetryStatus } from '@/db/schema/session-plan-helpers'

/**
 * State for redoing a previously completed problem
 * Allows students to tap any completed problem dot to practice it again
 */
export interface RedoState {
  /** Whether redo mode is currently active */
  isActive: boolean
  /** Linear index of the problem being redone (flat across all parts) */
  linearIndex: number
  /** Part index containing the redo problem */
  originalPartIndex: number
  /** Slot index within the part */
  originalSlotIndex: number
  /** The original result (to check if it was correct) */
  originalResult: SlotResult
  /** Part index to return to after redo */
  returnToPartIndex: number
  /** Slot index to return to after redo */
  returnToSlotIndex: number
}
import {
  type BreakContext,
  type ReceivedAbacusControl,
  type TeacherPauseRequest,
  useSessionBroadcast,
} from '@/hooks/useSessionBroadcast'
import {
  useAcknowledgeGameBreakResults,
  useCompletePartTransition,
  useFinishGameBreak,
  useStartGameBreak,
  sessionPlanKeys,
  useActiveSessionPlan,
  useEndSessionEarly,
  useRecordRedoResult,
  useRecordSlotResult,
} from '@/hooks/useSessionPlan'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useSaveGameResult } from '@/hooks/useGameResults'
import { useSessionMode } from '@/hooks/useSessionMode'
import { useSessionSongTrigger } from '@/hooks/useSessionSongTrigger'
import { BroadcastDebugPanel } from '@/components/debug/BroadcastDebugPanel'
import { css } from '../../../../styled-system/css'

interface PracticeClientProps {
  studentId: string
  player: Player
  initialSession: SessionPlan
  /** Whether session song generation is available (feature flag + family tier) */
  songEnabled?: boolean
}

/**
 * Practice Client Component
 *
 * This component ONLY shows the current problem.
 * It assumes the session is in_progress (server guards ensure this).
 *
 * When the session completes, it redirects to /summary.
 */
export function PracticeClient({
  studentId,
  player,
  initialSession,
  songEnabled = false,
}: PracticeClientProps) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { showError } = useToast()
  const { setVisionFrameCallback } = useMyAbacus()
  const queryClient = useQueryClient()

  // Track pause state for HUD display (ActiveSession owns the modal and actual pause logic)
  const [isPaused, setIsPaused] = useState(false)
  // Track timing data from ActiveSession for the sub-nav HUD
  const [timingData, setTimingData] = useState<AttemptTimingData | null>(null)
  // Track broadcast state for session observation (digit-by-digit updates from ActiveSession)
  const [broadcastState, setBroadcastState] = useState<BroadcastState | null>(null)
  // Browse mode state - lifted here so PracticeSubNav can trigger it
  const [isBrowseMode, setIsBrowseMode] = useState(false)
  // Browse index - lifted for navigation from SessionProgressIndicator
  const [browseIndex, setBrowseIndex] = useState(0)
  // Teacher abacus control - receives commands from observing teacher
  const [teacherControl, setTeacherControl] = useState<ReceivedAbacusControl | null>(null)
  // Teacher-initiated pause/resume requests from observing teacher
  const [teacherPauseRequest, setTeacherPauseRequest] = useState<TeacherPauseRequest | null>(null)
  const [teacherResumeRequest, setTeacherResumeRequest] = useState(false)
  // Manual pause request from HUD
  const [manualPauseRequest, setManualPauseRequest] = useState(false)
  // Local fallback start time for game break HUD while persisted state catches up
  const [gameBreakStartTime, setGameBreakStartTime] = useState<number>(Date.now())
  // Game break results - captured when game completes to show on interstitial screen
  const [gameBreakResults, setGameBreakResults] = useState<GameResultsReport | null>(null)
  // Track previous part index to detect part transitions
  const previousPartIndexRef = useRef<number>(initialSession.currentPartIndex)
  // Ref to store stopVisionRecording - populated later when useSessionBroadcast is called
  // This allows early-defined callbacks to access the function
  const stopRecordingRef = useRef<(() => void) | undefined>(undefined)
  // Ref to store sendProblemMarker for timeline sync
  const sendProblemMarkerRef = useRef<
    | ((
        problemNumber: number,
        partIndex: number,
        eventType: 'problem-shown' | 'answer-submitted' | 'feedback-shown',
        isCorrect?: boolean,
        retryContext?: {
          epochNumber: number
          attemptNumber: number
          isRetry: boolean
          isManualRedo: boolean
        },
        slotId?: string,
        problem?: { terms: number[]; answer: number }
      ) => void)
    | undefined
  >(undefined)
  // Redo state - allows students to re-attempt any completed problem
  const [redoState, setRedoState] = useState<RedoState | null>(null)
  // Break context for observer broadcast — updated by GameBreakScreen callbacks
  const [breakContext, setBreakContext] = useState<BreakContext | null>(null)

  const gameBreakTraceEnabled = searchParams.get('debugGameBreakTrace') === '1'

  // Session plan mutations
  const recordResult = useRecordSlotResult()
  const recordRedo = useRecordRedoResult()
  const endEarly = useEndSessionEarly()
  const completePartTransition = useCompletePartTransition()
  const startGameBreak = useStartGameBreak()
  const finishGameBreak = useFinishGameBreak()
  const acknowledgeGameBreakResults = useAcknowledgeGameBreakResults()

  // Game results mutation - saves to scoreboard when game break completes
  const saveGameResult = useSaveGameResult()

  // Fetch active session plan from cache or API with server data as initial
  const { data: fetchedPlan } = useActiveSessionPlan(studentId, initialSession)

  // Current plan should come from the active-session query cache.
  // Each mutation writes back to this cache on success.
  // Do not prioritize mutation-local `data`, which can become stale and mask newer flow updates.
  const currentPlan = fetchedPlan ?? initialSession

  // Fetch historical results from prior completed sessions for threshold calculation.
  // This enables complexity-scaled auto-pause thresholds from session start.
  const { data: historicalResults } = useQuery({
    queryKey: ['problem-history', studentId],
    queryFn: async () => {
      const res = await fetch(`/api/curriculum/${studentId}/problem-history`)
      if (!res.ok) return []
      const data = await res.json()
      return (data.history ?? []) as SlotResult[]
    },
    staleTime: 5 * 60 * 1000, // 5 minutes — historical data doesn't change during a session
  })
  const logGameBreakTrace = useCallback(
    (event: string, details: Record<string, unknown> = {}) => {
      if (!gameBreakTraceEnabled) return
      console.log('[GBTRACE][client]', event, {
        ts: new Date().toISOString(),
        studentId,
        planId: currentPlan.id,
        ...details,
      })
    },
    [gameBreakTraceEnabled, studentId, currentPlan.id]
  )

  // Game break settings from the session plan
  const gameBreakSettings = currentPlan.gameBreakSettings as GameBreakSettings | null
  const flowState = currentPlan.flowState ?? 'practicing'
  const showGameBreak = flowState === 'break_pending' || flowState === 'break_active'
  const showGameBreakResults = flowState === 'break_results'

  useEffect(() => {
    if (showGameBreak && currentPlan.breakStartedAt) {
      setGameBreakStartTime(new Date(currentPlan.breakStartedAt).getTime())
    }
  }, [showGameBreak, currentPlan.breakStartedAt])

  useEffect(() => {
    if (!showGameBreakResults) return

    const persistedResults = currentPlan.breakResults ?? null
    if (persistedResults && !gameBreakResults) {
      setGameBreakResults(persistedResults)
      return
    }

    if (gameBreakResults || persistedResults) return

    acknowledgeGameBreakResults.mutate({
      playerId: studentId,
      planId: currentPlan.id,
      expectedFlowVersion: currentPlan.flowVersion,
    })
  }, [
    showGameBreakResults,
    gameBreakResults,
    currentPlan.breakResults,
    currentPlan.flowVersion,
    acknowledgeGameBreakResults,
    studentId,
    currentPlan.id,
  ])

  // Build game config with skipSetupPhase merged into each game's config
  // This allows games to start immediately without showing their setup screen
  const gameBreakGameConfig = useMemo(() => {
    const baseConfig = gameBreakSettings?.gameConfig ?? {}
    const skipSetup = gameBreakSettings?.skipSetupPhase ?? true // Default to true for practice breaks

    if (!skipSetup) {
      return baseConfig
    }

    // Merge skipSetupPhase + practice-break metadata into each game's config
    const practiceBreakMeta = {
      skipSetupPhase: true,
      maxDurationMinutes: gameBreakSettings?.maxDurationMinutes ?? 5,
      playerName: player.name,
    }
    const mergedConfig: Record<string, Record<string, unknown>> = {}
    for (const [gameName, config] of Object.entries(baseConfig)) {
      mergedConfig[gameName] = { ...config, ...practiceBreakMeta }
    }

    // Also add metadata for the selected game if not already in config
    const selectedGame = gameBreakSettings?.selectedGame
    if (selectedGame && selectedGame !== 'random' && !mergedConfig[selectedGame]) {
      mergedConfig[selectedGame] = { ...practiceBreakMeta }
    }

    return mergedConfig
  }, [
    gameBreakSettings?.gameConfig,
    gameBreakSettings?.skipSetupPhase,
    gameBreakSettings?.selectedGame,
    gameBreakSettings?.maxDurationMinutes,
    player.name,
  ])

  // Compute HUD data from current plan
  const currentPart = currentPlan.parts[currentPlan.currentPartIndex] as SessionPart | undefined
  const sessionHealth = currentPlan.sessionHealth as SessionHealth | null

  // Calculate totals
  const { totalProblems, completedProblems } = useMemo(() => {
    const total = currentPlan.parts.reduce((sum, part) => sum + part.slots.length, 0)
    let completed = 0
    for (let i = 0; i < currentPlan.currentPartIndex; i++) {
      completed += currentPlan.parts[i].slots.length
    }
    completed += currentPlan.currentSlotIndex
    return { totalProblems: total, completedProblems: completed }
  }, [currentPlan.parts, currentPlan.currentPartIndex, currentPlan.currentSlotIndex])

  // Helper to compute retry context for video recording
  const getRetryContext = useCallback(
    (partIndex: number, slotIndex: number) => {
      // Check if we're in a manual redo
      const isManualRedo = redoState?.isActive && redoState?.originalSlotIndex === slotIndex

      // Get epoch from retry state
      const retryState = currentPlan.retryState as SessionRetryState | null
      const epochNumber = retryState?.[partIndex]?.currentEpoch ?? 0

      // Count attempts for this slot to determine attemptNumber
      const { attemptCount } = getSlotRetryStatus(currentPlan, partIndex, slotIndex)
      // attemptNumber is the next attempt (current attempt count + 1)
      const attemptNumber = attemptCount + 1

      return {
        epochNumber,
        attemptNumber,
        isRetry: epochNumber > 0,
        isManualRedo: isManualRedo ?? false,
      }
    },
    [currentPlan, redoState]
  )

  // Pause handler - triggers manual pause in ActiveSession
  const handlePause = useCallback(() => {
    setManualPauseRequest(true)
  }, [])

  const handleResume = useCallback(() => {
    setIsPaused(false)
  }, [])

  // Mutation queue: each server mutation chains off the previous one so they
  // execute in order. The UI can advance optimistically while mutations queue.
  const pendingMutationRef = useRef<Promise<void>>(Promise.resolve())

  // Handle recording an answer
  const handleAnswer = useCallback(
    (result: Omit<SlotResult, 'timestamp' | 'partNumber'>): Promise<void> => {
      // Synchronous work: problem markers + trace logging happen immediately
      const currentProblemNumber = currentPlan.currentSlotIndex + 1
      const retryContext = getRetryContext(
        currentPlan.currentPartIndex,
        currentPlan.currentSlotIndex
      )
      sendProblemMarkerRef.current?.(
        currentProblemNumber,
        currentPlan.currentPartIndex,
        'answer-submitted',
        result.isCorrect,
        retryContext
      )
      logGameBreakTrace('answer-submit-start', {
        currentProblemNumber,
        currentPartIndex: currentPlan.currentPartIndex,
        currentSlotIndex: currentPlan.currentSlotIndex,
        isCorrect: result.isCorrect,
      })

      // Capture values that the mutation closure needs
      const capturedPreviousPartIndex = previousPartIndexRef.current

      // Chain this mutation onto the queue so mutations execute in order
      const mutationPromise = pendingMutationRef.current.then(async () => {
        try {
          const updatedPlan = await recordResult.mutateAsync({
            playerId: studentId,
            planId: currentPlan.id,
            result,
          })
          logGameBreakTrace('answer-submit-resolved', {
            previousPartIndex: capturedPreviousPartIndex,
            updatedPartIndex: updatedPlan.currentPartIndex,
            updatedSlotIndex: updatedPlan.currentSlotIndex,
            updatedStatus: updatedPlan.status,
            completedAt: updatedPlan.completedAt ? String(updatedPlan.completedAt) : null,
          })

          // Update previous part index tracking
          previousPartIndexRef.current = updatedPlan.currentPartIndex

          // If session just completed, redirect to summary with completed flag
          if (updatedPlan.completedAt) {
            stopRecordingRef.current?.()
            router.push(`/practice/${studentId}/summary?completed=1`, {
              scroll: false,
            })
            return
          }

          // Check for part transition for trace visibility
          const partTransitioned = updatedPlan.currentPartIndex > capturedPreviousPartIndex
          const hasMoreParts = updatedPlan.currentPartIndex < updatedPlan.parts.length
          const gameBreakEnabled =
            (updatedPlan.gameBreakSettings as GameBreakSettings | null)?.enabled ?? false

          if (partTransitioned && hasMoreParts && gameBreakEnabled) {
            logGameBreakTrace('queue-break-after-part-transition', {
              previousPartIndex: capturedPreviousPartIndex,
              updatedPartIndex: updatedPlan.currentPartIndex,
              hasMoreParts,
              gameBreakEnabled,
            })
          } else {
            logGameBreakTrace('no-break-queue-after-answer', {
              partTransitioned,
              hasMoreParts,
              gameBreakEnabled,
            })
          }
        } catch (err) {
          const message = err instanceof Error ? err.message : 'Unknown error'
          if (message.includes('Not authorized')) {
            showError(
              'Not authorized',
              'Only parents or teachers with the student present in their classroom can record answers.'
            )
          } else {
            showError('Failed to record answer', message)
          }
        }
      })

      pendingMutationRef.current = mutationPromise
      return mutationPromise
    },
    [
      studentId,
      currentPlan.id,
      currentPlan.currentPartIndex,
      currentPlan.currentSlotIndex,
      recordResult,
      router,
      showError,
      logGameBreakTrace,
      getRetryContext,
    ]
  )

  // Handle ending session early
  const handleEndEarly = useCallback(
    async (reason?: string) => {
      try {
        await endEarly.mutateAsync({
          playerId: studentId,
          planId: currentPlan.id,
          reason,
        })
        // Stop vision recording if it was started
        stopRecordingRef.current?.()
        // Redirect to summary after ending early with completed flag
        router.push(`/practice/${studentId}/summary?completed=1`, {
          scroll: false,
        })
      } catch (err) {
        // Check if it's an authorization error
        const message = err instanceof Error ? err.message : 'Unknown error'
        if (message.includes('Not authorized')) {
          showError(
            'Not authorized',
            'Only parents or teachers with the student present in their classroom can end sessions.'
          )
        } else {
          showError('Failed to end session', message)
        }
      }
    },
    [studentId, currentPlan.id, endEarly, router, showError]
  )

  // Handle session completion (called by ActiveSession when all problems done)
  const handleSessionComplete = useCallback(() => {
    // Stop vision recording if it was started
    stopRecordingRef.current?.()
    // Redirect to summary with completed flag
    router.push(`/practice/${studentId}/summary?completed=1`, {
      scroll: false,
    })
  }, [studentId, router])

  // Handle redoing a previously completed problem
  // Called when student taps a completed problem dot in the progress indicator
  const handleRedoProblem = useCallback(
    (linearIndex: number, originalResult: SlotResult) => {
      // Find the part and slot for this linear index
      let partIndex = 0
      let remaining = linearIndex
      for (let i = 0; i < currentPlan.parts.length; i++) {
        const partSlotCount = currentPlan.parts[i].slots.length
        if (remaining < partSlotCount) {
          partIndex = i
          break
        }
        remaining -= partSlotCount
      }
      const slotIndex = remaining

      // Exit browse mode if active
      if (isBrowseMode) {
        setIsBrowseMode(false)
      }

      // Set redo state
      setRedoState({
        isActive: true,
        linearIndex,
        originalPartIndex: partIndex,
        originalSlotIndex: slotIndex,
        originalResult,
        returnToPartIndex: currentPlan.currentPartIndex,
        returnToSlotIndex: currentPlan.currentSlotIndex,
      })
    },
    [currentPlan.parts, currentPlan.currentPartIndex, currentPlan.currentSlotIndex, isBrowseMode]
  )

  // Handle canceling a redo - exit without recording
  const handleCancelRedo = useCallback(() => {
    setRedoState(null)
  }, [])

  // Handle redo result recording - wraps recordRedo to send answer-submitted marker
  const handleRecordRedo = useCallback(
    async (params: {
      playerId: string
      planId: string
      result: Omit<SlotResult, 'timestamp' | 'partNumber'>
      redoContext: {
        originalPartIndex: number
        originalSlotIndex: number
        originalWasCorrect: boolean
      }
    }): Promise<SessionPlan> => {
      // Send the answer-submitted marker for the redo
      const { redoContext, result } = params
      const retryContext = getRetryContext(
        redoContext.originalPartIndex,
        redoContext.originalSlotIndex
      )
      const currentProblemNumber = redoContext.originalSlotIndex + 1
      sendProblemMarkerRef.current?.(
        currentProblemNumber,
        redoContext.originalPartIndex,
        'answer-submitted',
        result.isCorrect,
        retryContext
      )

      // Now call the actual mutation
      return recordRedo.mutateAsync(params)
    },
    [getRetryContext, recordRedo]
  )

  // Handle game break end - show results screen if game finished normally
  const handleGameBreakEnd = useCallback(
    (reason: 'timeout' | 'gameFinished' | 'skipped', results?: GameResultsReport) => {
      // If game finished normally with results, save to scoreboard and show interstitial
      if (reason === 'gameFinished' && results) {
        // Save result to database for scoreboard
        const savePayload = {
          playerId: player.id,
          sessionType: 'practice-break' as const,
          sessionId: currentPlan.id,
          report: results,
        }
        console.info('[handleGameBreakEnd] Saving game result:', {
          playerId: savePayload.playerId,
          sessionType: savePayload.sessionType,
          sessionId: savePayload.sessionId,
          gameName: results.gameName,
        })
        saveGameResult.mutate(savePayload)

        setGameBreakResults(results)
      } else {
        // Timeout or skip - no results to show, return to practice immediately
        setGameBreakResults(null)
      }

      void finishGameBreak
        .mutateAsync({
          playerId: studentId,
          planId: currentPlan.id,
          breakFinishReason: reason,
          breakResults: results ?? null,
          expectedFlowVersion: currentPlan.flowVersion,
        })
        .then((updatedPlan) => {
          logGameBreakTrace('game-break-finish-resolved', {
            reason,
            updatedFlowState: updatedPlan.flowState,
            updatedBreakReason: updatedPlan.breakReason,
          })
        })
        .catch((err) => {
          showError(
            'Failed to finish game break',
            err instanceof Error ? err.message : 'Unknown error'
          )
        })
    },
    [
      saveGameResult,
      player.id,
      currentPlan.id,
      currentPlan.flowVersion,
      finishGameBreak,
      studentId,
      logGameBreakTrace,
      showError,
    ]
  )

  const handleGameBreakStarted = useCallback(
    (gameName: string) => {
      void startGameBreak
        .mutateAsync({
          playerId: studentId,
          planId: currentPlan.id,
          game: gameName,
          expectedFlowVersion: currentPlan.flowVersion,
        })
        .catch((err) => {
          logGameBreakTrace('game-break-start-failed', {
            gameName,
            error: err instanceof Error ? err.message : String(err),
          })
        })
    },
    [startGameBreak, studentId, currentPlan.id, currentPlan.flowVersion, logGameBreakTrace]
  )

  // Handle results screen completion - return to practice
  const handleGameBreakResultsComplete = useCallback(() => {
    setGameBreakResults(null)
    void acknowledgeGameBreakResults
      .mutateAsync({
        playerId: studentId,
        planId: currentPlan.id,
        expectedFlowVersion: currentPlan.flowVersion,
      })
      .then((updatedPlan) => {
        logGameBreakTrace('game-break-results-acked', {
          updatedFlowState: updatedPlan.flowState,
        })
      })
      .catch((err) => {
        showError(
          'Failed to return to practice',
          err instanceof Error ? err.message : 'Unknown error'
        )
      })
  }, [
    acknowledgeGameBreakResults,
    studentId,
    currentPlan.id,
    currentPlan.flowVersion,
    logGameBreakTrace,
    showError,
  ])

  // Broadcast session state if student is in a classroom
  // broadcastState is updated by ActiveSession via the onBroadcastStateChange callback
  // onAbacusControl receives control events from observing teacher
  // onTeacherPause/onTeacherResume receive pause/resume commands from teacher
  const {
    isConnected: broadcastConnected,
    isBroadcasting,
    sendPartTransition,
    sendPartTransitionComplete,
    sendVisionFrame,
    isRecording,
    recordingId,
    startVisionRecording,
    stopVisionRecording,
    sendProblemMarker,
    readyObservers,
  } = useSessionBroadcast(currentPlan.id, studentId, broadcastState, flowState, breakContext, {
    onAbacusControl: setTeacherControl,
    onTeacherPause: setTeacherPauseRequest,
    onTeacherResume: () => setTeacherResumeRequest(true),
  })

  // Session song smart trigger — fires when conditions are met mid-session
  useSessionSongTrigger({ studentId, plan: currentPlan, songEnabled })

  // Focus skill banner — show the math rule(s) the student is working on
  const { data: sessionModeData } = useSessionMode(studentId)
  const focusSkills = useMemo((): string[] | undefined => {
    if (!sessionModeData) return undefined
    const mode = sessionModeData.sessionMode
    switch (mode.type) {
      case 'progression':
        return mode.nextSkill.hasMathSentence ? [mode.nextSkill.displayName] : undefined
      case 'remediation': {
        const mathSkills = mode.weakSkills
          .filter((s) => s.hasMathSentence)
          .map((s) => s.displayName)
        return mathSkills.length > 0 ? mathSkills : undefined
      }
      case 'maintenance':
        return undefined
    }
  }, [sessionModeData])

  // Track whether we've started vision recording for this session
  const hasStartedRecordingRef = useRef(false)
  // Track previous problem number to detect when new problems appear
  const previousProblemNumberRef = useRef<number | null>(null)
  // Track previous isRecording state to detect when recording starts
  const wasRecordingRef = useRef(false)
  // Update the refs so callbacks defined earlier can access these functions
  stopRecordingRef.current = stopVisionRecording
  sendProblemMarkerRef.current = sendProblemMarker

  // When recording starts, emit problem-shown marker for the current problem
  // This handles the case where recording starts mid-session after the first problem-shown was dropped
  useEffect(() => {
    const wasRecording = wasRecordingRef.current
    wasRecordingRef.current = isRecording

    // Detect transition from not-recording to recording
    if (!wasRecording && isRecording && broadcastState) {
      const currentProblemNumber = broadcastState.currentProblemNumber
      const partIndex = broadcastState.currentPartIndex ?? currentPlan.currentPartIndex
      const slotIndex = broadcastState.currentSlotIndex ?? currentPlan.currentSlotIndex
      const retryContext = getRetryContext(partIndex, slotIndex)
      sendProblemMarker(
        currentProblemNumber,
        partIndex,
        'problem-shown',
        undefined,
        retryContext,
        broadcastState.slotId,
        broadcastState.currentProblem
      )
    }
  }, [
    isRecording,
    broadcastState,
    currentPlan.currentPartIndex,
    currentPlan.currentSlotIndex,
    sendProblemMarker,
    getRetryContext,
  ])

  // Emit 'problem-shown' marker when a new problem appears (including first problem)
  useEffect(() => {
    if (!broadcastState) return

    const currentProblemNumber = broadcastState.currentProblemNumber
    const previousProblemNumber = previousProblemNumberRef.current

    // Emit if this is a new problem OR the first problem (previousProblemNumber is null)
    if (currentProblemNumber !== previousProblemNumber) {
      // broadcastState contains the correct slot indices (including for redos)
      const partIndex = broadcastState.currentPartIndex ?? currentPlan.currentPartIndex
      const slotIndex = broadcastState.currentSlotIndex ?? currentPlan.currentSlotIndex
      const retryContext = getRetryContext(partIndex, slotIndex)
      sendProblemMarker(
        currentProblemNumber,
        partIndex,
        'problem-shown',
        undefined,
        retryContext,
        broadcastState.slotId,
        broadcastState.currentProblem
      )
    }

    // Update ref for next comparison
    previousProblemNumberRef.current = currentProblemNumber
  }, [
    broadcastState?.currentProblemNumber,
    broadcastState?.currentPartIndex,
    broadcastState?.currentSlotIndex,
    currentPlan.currentPartIndex,
    currentPlan.currentSlotIndex,
    sendProblemMarker,
    getRetryContext,
  ])

  // Emit 'problem-shown' marker when entering redo mode
  // The regular problem-shown effect won't fire because currentProblemNumber doesn't change during a redo
  const wasInRedoModeRef = useRef(false)
  useEffect(() => {
    const wasInRedoMode = wasInRedoModeRef.current
    const isNowInRedoMode = redoState?.isActive ?? false
    wasInRedoModeRef.current = isNowInRedoMode

    // Detect entering redo mode
    if (!wasInRedoMode && isNowInRedoMode && redoState) {
      const retryContext = getRetryContext(redoState.originalPartIndex, redoState.originalSlotIndex)
      const problemNumber = redoState.linearIndex + 1 // linearIndex is 0-based
      // Get problem identity from the plan for the redo slot
      const redoPart = currentPlan.parts[redoState.originalPartIndex]
      const redoSlot = redoPart?.slots?.[redoState.originalSlotIndex]
      sendProblemMarker(
        problemNumber,
        redoState.originalPartIndex,
        'problem-shown',
        undefined,
        retryContext,
        redoSlot?.slotId,
        redoSlot?.problem
      )
    }
  }, [redoState, sendProblemMarker, getRetryContext, currentPlan.parts])

  const handlePartTransition = useCallback(
    (
      previousPartType: 'abacus' | 'visualization' | 'linear' | null,
      nextPartType: 'abacus' | 'visualization' | 'linear',
      countdownStartTime: number,
      countdownDurationMs: number
    ) => {
      logGameBreakTrace('part-transition-start', {
        previousPartType,
        nextPartType,
        countdownStartTime,
        countdownDurationMs,
      })
      sendPartTransition(previousPartType, nextPartType, countdownStartTime, countdownDurationMs)
    },
    [sendPartTransition, logGameBreakTrace]
  )

  // Handle part transition complete - called when transition screen finishes
  const handlePartTransitionComplete = useCallback(async () => {
    logGameBreakTrace('part-transition-complete-callback', {
      flowStateBefore: flowState,
      currentPartIndex: currentPlan.currentPartIndex,
      currentSlotIndex: currentPlan.currentSlotIndex,
    })
    sendPartTransitionComplete()
    try {
      const shouldRunBreak =
        ((currentPlan.gameBreakSettings as GameBreakSettings | null)?.enabled ?? false) &&
        currentPlan.currentPartIndex < currentPlan.parts.length
      const updatedPlan = await completePartTransition.mutateAsync({
        playerId: studentId,
        planId: currentPlan.id,
        expectedFlowVersion: currentPlan.flowVersion,
        shouldRunBreak,
      })
      logGameBreakTrace('part-transition-complete-resolved', {
        updatedFlowState: updatedPlan.flowState,
        updatedBreakStartedAt: updatedPlan.breakStartedAt,
      })
    } catch (err) {
      showError(
        'Failed to transition session',
        err instanceof Error ? err.message : 'Unknown transition error'
      )
    }
  }, [
    sendPartTransitionComplete,
    flowState,
    completePartTransition,
    studentId,
    currentPlan.id,
    currentPlan.flowVersion,
    currentPlan.currentPartIndex,
    currentPlan.currentSlotIndex,
    currentPlan.parts.length,
    currentPlan.gameBreakSettings,
    logGameBreakTrace,
    showError,
  ])

  // Wire vision frame callback to broadcast vision frames to observers
  // Also auto-start recording when vision frames start flowing
  useEffect(() => {
    setVisionFrameCallback((frame) => {
      // Start recording on first vision frame (if not already recording)
      if (!hasStartedRecordingRef.current && !isRecording) {
        hasStartedRecordingRef.current = true
        startVisionRecording()
      }

      sendVisionFrame(frame.imageData, frame.detectedValue, frame.confidence)
    })

    return () => {
      setVisionFrameCallback(null)
    }
  }, [setVisionFrameCallback, sendVisionFrame, isRecording, startVisionRecording])

  useEffect(() => {
    logGameBreakTrace('flow-state', { flowState, showGameBreak, showGameBreakResults })
  }, [flowState, showGameBreak, showGameBreakResults, logGameBreakTrace])

  // Build session HUD data for PracticeSubNav
  const sessionHud: SessionHudData | undefined = currentPart
    ? {
        isPaused,
        parts: currentPlan.parts,
        currentPartIndex: currentPlan.currentPartIndex,
        currentPart: {
          type: currentPart.type,
          partNumber: currentPart.partNumber,
          totalSlots: currentPart.slots.length,
        },
        currentSlotIndex: currentPlan.currentSlotIndex,
        results: currentPlan.results,
        completedProblems,
        totalProblems,
        sessionHealth: sessionHealth
          ? {
              overall: sessionHealth.overall,
              accuracy: sessionHealth.accuracy,
            }
          : undefined,
        // Pass timing data for the current problem
        timing: timingData
          ? {
              startTime: timingData.startTime,
              accumulatedPauseMs: timingData.accumulatedPauseMs,
              results: currentPlan.results,
              parts: currentPlan.parts,
            }
          : undefined,
        onPause: handlePause,
        onResume: handleResume,
        onEndEarly: () => handleEndEarly('Session ended'),
        isEndingSession: endEarly.isPending,
        isBrowseMode,
        onToggleBrowse: () => setIsBrowseMode((prev) => !prev),
        onBrowseNavigate: setBrowseIndex,
        onRedoProblem: handleRedoProblem, // Allow navigating to other problems during redo
        onCancelRedo: handleCancelRedo, // Return to current session position from redo
        redoLinearIndex: redoState?.linearIndex,
        plan: currentPlan,
      }
    : undefined

  // Build game break HUD data for PracticeSubNav (when on game break)
  const gameBreakHud: GameBreakHudData | undefined = showGameBreak
    ? {
        startTime: gameBreakStartTime,
        maxDurationMs: (gameBreakSettings?.maxDurationMinutes ?? 5) * 60 * 1000,
        onSkip: () => handleGameBreakEnd('skipped'),
      }
    : undefined

  return (
    <PageWithNav>
      {/* Practice Sub-Navigation with Session HUD or Game Break HUD */}
      <PracticeSubNav
        student={player}
        pageContext="session"
        sessionHud={sessionHud}
        gameBreakHud={gameBreakHud}
        focusSkills={focusSkills}
      />

      <main
        data-component="practice-page"
        className={`${css({
          userSelect: 'none',
          // Fixed positioning to precisely control bounds
          position: 'fixed',
          // Top: main nav (80px) + sub-nav height (~52px mobile, ~60px desktop) + optional focus banner (~24px)
          top: focusSkills ? { base: '156px', md: '164px' } : { base: '132px', md: '140px' },
          left: 0,
          // Right: 0 by default, landscape mobile handled via media query below
          right: 0,
          // Bottom: keypad height on mobile portrait (48px), 0 on desktop
          // Landscape mobile handled via media query below
          bottom: { base: '48px', md: 0 },
          overflow: 'hidden', // Prevent scrolling during practice
        })} no-text-select`}
      >
        {/* Landscape mobile: keypad is on right (100px) instead of bottom */}
        <style
          dangerouslySetInnerHTML={{
            __html: `
              @media (orientation: landscape) and (max-height: 500px) {
                [data-component="practice-page"] {
                  bottom: 0 !important;
                  right: 100px !important;
                }
              }
            `,
          }}
        />
        <PracticeErrorBoundary studentName={player.name}>
          {showGameBreakResults && gameBreakResults ? (
            <GameBreakResultsScreen
              isVisible={showGameBreakResults}
              results={gameBreakResults}
              student={{ name: player.name, emoji: player.emoji }}
              onComplete={handleGameBreakResultsComplete}
            />
          ) : showGameBreak ? (
            <GameBreakScreen
              isVisible={showGameBreak}
              student={{
                id: player.id,
                name: player.name,
                emoji: player.emoji,
                color: player.color,
              }}
              maxDurationMinutes={gameBreakSettings?.maxDurationMinutes ?? 5}
              startTime={gameBreakStartTime}
              onComplete={handleGameBreakEnd}
              selectionMode={gameBreakSettings?.selectionMode ?? 'kid-chooses'}
              selectedGame={gameBreakSettings?.selectedGame ?? null}
              gameConfig={gameBreakGameConfig}
              enabledGames={gameBreakSettings?.enabledGames}
              onGameSelected={handleGameBreakStarted}
              onBreakContextChange={setBreakContext}
              readyObservers={readyObservers}
            />
          ) : (
            <ActiveSession
              plan={currentPlan}
              historicalResults={historicalResults}
              student={{
                id: player.id,
                name: player.name,
                emoji: player.emoji,
                color: player.color,
              }}
              onAnswer={handleAnswer}
              onEndEarly={handleEndEarly}
              onPause={() => setIsPaused(true)}
              onResume={handleResume}
              onComplete={handleSessionComplete}
              onTimingUpdate={setTimingData}
              onBroadcastStateChange={setBroadcastState}
              isBrowseMode={isBrowseMode}
              browseIndex={browseIndex}
              onBrowseIndexChange={setBrowseIndex}
              teacherControl={teacherControl}
              onTeacherControlHandled={() => setTeacherControl(null)}
              teacherPauseRequest={teacherPauseRequest}
              onTeacherPauseHandled={() => setTeacherPauseRequest(null)}
              teacherResumeRequest={teacherResumeRequest}
              onTeacherResumeHandled={() => setTeacherResumeRequest(false)}
              manualPauseRequest={manualPauseRequest}
              onManualPauseHandled={() => setManualPauseRequest(false)}
              onPartTransition={handlePartTransition}
              onPartTransitionComplete={handlePartTransitionComplete}
              redoState={redoState}
              onRecordRedo={handleRecordRedo}
              onRedoComplete={() => setRedoState(null)}
              onCancelRedo={handleCancelRedo}
              onResultEdited={() => {
                // Invalidate the session plan query to refetch updated results
                queryClient.invalidateQueries({
                  queryKey: sessionPlanKeys.active(studentId),
                })
              }}
            />
          )}
        </PracticeErrorBoundary>
      </main>

      {/* Debug panel for socket broadcast state - only visible when visual debug is enabled */}
      <BroadcastDebugPanel
        isConnected={broadcastConnected}
        isBroadcasting={isBroadcasting}
        isRecording={isRecording}
        sessionId={currentPlan.id}
        playerId={studentId}
        recordingId={recordingId}
        broadcastState={broadcastState}
      />
    </PageWithNav>
  )
}